<?php

namespace App\Libs;

class Cache
{

    private $is_cache;

    private $cache_file;

    private $cache_time;

    function __construct($config = [])
    {
        //定义是否开启缓存
        $this->is_cache = isset($config['is_cache'])?$config['is_cache']:0;
        //定义缓存目录
        $this->cache_file = getFolder(__DIR__ . 'kkw') . (isset($config['cache_file'])?$config['cache_file']:'/bootstrap/');
        //定义缓存时间
        $this->cache_time = isset($config['cache_time'])?$config['cache_time']:60;
    }

    /**
     * 读取缓存文件
     * @param $name
     * @return bool|mixed
     */
    public function open($name)
    {
        $arr = array();
        $filename = $this->cache_file . $name;
        $status = filemtime($filename) + $this->cache_time > time();//定义缓存时间
        if (file_exists($filename) && $status && $this->is_cache) {
            $content = file_get_contents($filename);//读取缓存文件
            $arr = unserialize($content);
            return $arr;
        } else {
            return false;
        }
    }

    /**
     * 打开所有文件
     * @param string $file_path
     * @return array
     */
    public function openAll($file_path = '')
    {
        $files = [];
        $allFile = getDirectoryToArray($file_path);
        foreach ($allFile as $v) {
            $files[] = self::open($v);
        }
        return $files;
    }

    /**
     * 写入缓存文件
     * @param $name
     * @param array $data
     */
    public function write($name, $data = [])
    {
        createDirectory($this->cache_file);
        $filename = $this->cache_file . $name;
        $content = serialize($data);
        file_put_contents($filename, $content);//写入缓存文件
    }
}
